package com.example.rocketmq.demo.producer;

import com.example.rocketmq.demo.config.RocketMQConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 普通消息生产者
 */
@Slf4j
@Component
public class NormalProducer {

    @Autowired
    @Qualifier("defaultMQProducer")
    private DefaultMQProducer producer;

    /**
     * 同步发送消息
     *
     * @param content 消息内容
     * @return 发送结果
     */
    public SendResult sendSync(String content) throws Exception {
        Message message = new Message(
                RocketMQConstant.TOPIC_NORMAL,
                RocketMQConstant.TAG_NORMAL,
                content.getBytes(StandardCharsets.UTF_8)
        );

        SendResult sendResult = producer.send(message);
        log.info("同步发送消息结果: {}", sendResult);
        return sendResult;
    }

    /**
     * 异步发送消息
     *
     * @param content 消息内容
     */
    public void sendAsync(String content) throws Exception {
        Message message = new Message(
                RocketMQConstant.TOPIC_NORMAL,
                RocketMQConstant.TAG_NORMAL,
                content.getBytes(StandardCharsets.UTF_8)
        );

        producer.send(message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("异步发送消息成功: {}", sendResult);
            }

            @Override
            public void onException(Throwable e) {
                log.error("异步发送消息失败", e);
            }
        });
    }

    /**
     * 单向发送消息（不关心发送结果）
     *
     * @param content 消息内容
     */
    public void sendOneWay(String content) throws Exception {
        Message message = new Message(
                RocketMQConstant.TOPIC_NORMAL,
                RocketMQConstant.TAG_NORMAL,
                content.getBytes(StandardCharsets.UTF_8)
        );

        producer.sendOneway(message);
        log.info("单向发送消息完成");
    }
}
